package com.zx.redis.reactive.config;

import com.alibaba.fastjson2.support.spring6.data.redis.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * <p>
 * description: redis配置 <br>
 * create: 2024-08-20 14:32
 * </p>
 *
 * @author zhou  xun
 */
@Configuration
public class RedisReactiveConfig {

    /**
     * 配置ReactiveRedisTemplate，用于Redis的响应式操作
     *
     * @param connectionFactory Redis连接工厂
     * @return 配置好的ReactiveRedisTemplate实例
     */
    @Bean
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory) {
        // 创建StringRedisSerializer用于键的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // 创建FastJsonRedisSerializer用于值的序列化，这里指定了泛型为Object，可以根据需要调整
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);

        // 使用RedisSerializationContextBuilder来配置序列化上下文
        RedisSerializationContext.RedisSerializationContextBuilder builder = RedisSerializationContext.newSerializationContext();

        // 配置键的序列化方式
        builder.key(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer));

        // 配置值的序列化方式
        builder.value(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer));

        // 配置哈希键的序列化方式（这里使用默认的序列化器，通常是StringRedisSerializer，如果需要可以替换）
        builder.hashKey(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer));

        // 配置哈希值的序列化方式
        builder.hashValue(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer));

        // 构建序列化上下文
        RedisSerializationContext<Object, Object> serializationContext = builder.build();

        // 创建ReactiveRedisTemplate实例，并传入连接工厂和序列化上下文
        ReactiveRedisTemplate<Object, Object> template = new ReactiveRedisTemplate<>(connectionFactory, serializationContext);

        // 返回配置好的ReactiveRedisTemplate实例
        return template;
    }
}